package com.zyz.order.service;

import com.zyz.order.mapper.OrderMapper;
import com.zyz.order.model.OrderInfo;
import com.zyz.order.model.ProductInfo;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
@Service
public class OrderService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private RestTemplate restTemplate;

//    @Autowired
//    private DiscoveryClient discoveryClient;

//    // 线程安全的计数器（原子的）
//    private AtomicInteger count = new AtomicInteger(1);
//
//    private List<ServiceInstance> instances;
//    @PostConstruct  // 依赖注入完毕后调用@PostConstruct修饰的函数可以用作初始化一些内容
//    public void init() {
//        // 从Eureka中获取服务列表
//         instances = discoveryClient.getInstances("product-service");
//    }

//    public OrderInfo selectOrderById(Integer id) {
//        OrderInfo orderInfo = orderMapper.selectOrderById(id);
//
//        // 负载均衡（将计数器每次获取之后+1，对instances中的个数取模）
//        int index = count.getAndIncrement() % instances.size();
//        // 获取负载均衡后的uri
//        String uri = instances.get(index).getUri().toString();
//        // 拼接成url
//        String url = uri + "/product/" + orderInfo.getProductId();
//        log.info("远程调用url：{}",url);
//        ProductInfo getProductInfo = restTemplate.getForObject(url, ProductInfo.class);
//        orderInfo.setProductInfo(getProductInfo);
//        return orderInfo;
//    }

    public OrderInfo selectOrderById(Integer id) {
        OrderInfo orderInfo = orderMapper.selectOrderById(id);

        String url = "http://product-service/product/" + orderInfo.getProductId();
        log.info("远程调用url：{}",url);
        ProductInfo getProductInfo = restTemplate.getForObject(url, ProductInfo.class);
        orderInfo.setProductInfo(getProductInfo);
        return orderInfo;
    }
}
